<script setup>

</script>

<template>
  <el-card>
    <!-- 查询条件开始 -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input
            v-model="queryParams.data.roleName"
            placeholder="请输入角色名称"
            clearable
            size="small"
            style="width:240px"
        />
      </el-form-item>
      <el-form-item label="权限编码" prop="roleCode">
        <el-input
            v-model="queryParams.data.roleCode"
            placeholder="请输入权限编码"
            clearable
            size="small"
            style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
            v-model="queryParams.data.status"
            placeholder="可用状态"
            clearable
            size="small"
            style="width:240px">
          <el-option
              v-for="dict in statusDict"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
            v-model="queryParams.data.dateRange"
            size="small"
            style="width:240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholde="开始日期"
            end-placeholde="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 查询条件结束 -->
    <!-- 表格工具按钮开始 -->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
          批量删除
        </el-button>
      </el-col>
    </el-row>
    <!-- 表格工具按钮结束 -->

    <!-- 数据表格开始 -->
    <el-table v-loading="loading" border :data="roleTableList" @selection-change="handleSelectionChnage">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="角色ID" align="center" prop="roleId"/>
      <el-table-column label="角色名称" align="center" prop="roleName"/>
      <el-table-column label="权限编码" align="center" prop="roleCode"/>
      <el-table-column label="显示顺序" align="center" prop="roleSort"/>
      <el-table-column label="状态" prop="statusName" align="center"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200px"/>
      <el-table-column label="操作" align="center" width="280">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)" :disabled="single">
            删除
          </el-button>
          <el-button type="text" icon="el-icon-thumb" size="mini" @click="handleSelectMenu(scope.row)">
            分配权限
          </el-button>
        </template>
      </el-table-column>
      <!-- =============================分配权限弹出层开始=============================== -->
      <el-dialog
          :title="title"
          :visible.sync="selectMenuOpen"
          width="400px"
          center
          append-to-body
      >
        <el-tree
            ref="menu"
            :data="menuOptions"
            show-checkbox
            node-key="menuId"
            highlight-current
            empty-text="加载中，请稍后"
            :props="{id:'menuId',children:'children',label:'menuName'}"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelectMenuSubmit">确 定</el-button>
        <el-button @click="cancelSelectMenu">取 消</el-button>
      </span>
      </el-dialog>
      <!-- =========================分配权限和菜单弹出层结束====================================== -->
    </el-table>
    <!-- 数据表格结束 -->
    <!-- 分页控件开始 -->
    <el-pagination
        v-show="true"
        :current-page="queryParams.pageNo"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <!-- 分页控件结束 -->
    <!-- 添加修改弹出层开始 -->
    <el-dialog
        :title="title"
        :visible.sync="open"
        width="500px"
        center
        append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" clearable size="small"/>
        </el-form-item>
        <el-form-item label="权限编码" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入权限字符" clearable size="small"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" clearable size="small" :min="0"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in statusDict"
                :key="dict.dictValue"
                :label="dict.dictValue"
                :value="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入字典备注" clearable
                    size="small"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
import {ref} from "vue";

export default {
  data() {
    return {
      //sys_role_menu表字典
      roleMenuTree: [],
      //sys_menu表字典
      menuTree: [],
      //树形控件配置
      props: {
        label: 'menuName',
        children: 'zones'
      },
      // 是否启用遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: false,
      // 非多个禁用
      multiple: true,
      // 分页数据总条数
      total: 0,
      // 字典表格数据
      roleTableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //添加修改的状态显示
      statusDict: [],

      //树形控件所需的角色id
      treeId: undefined,

      //树形节点一
      nodeOne: [],

      //树状过度存参
      roleMenus: [],

      //回显数据
      menuData: [],

      nodes: [],

      // 日期范围
      dateRange: [],
      // 分配权限的菜单树数据
      treeProps: {
        id: 'menuId',
        children: 'children',
        label: 'menuName'
      },
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 5,
        total: 0,
        /*roleName: undefined,
        roleCode: undefined,
        status: undefined,
        dateRange: [],*/
        data:{}
      },
      // 表单数据
      form: {},
      // 表单校验
      rules: {
        roleName: [
          {required: true, message: '角色名称不能为空', trigger: 'blur'}
        ],
        roleCode: [
          {required: true, message: '权限编码不能为空', trigger: 'blur'}
        ]
      },
      // 是否打开分配权限的弹出层
      selectMenuOpen: false,
      // 菜单树的数据
      menuOptions: [],
      // 当前选中持角色ID
      currentRoleId: undefined,

    }
  },
  created() {
    this.getRoleList();
    this.loadStatus();
    this.statusFormatter();
   /* this.getRoleMenuTree();
    this.getMenuTree();*/
    //this.loadStatus();
   // this.getRoleMenuTree();
   // this.getMenuTree();
  },
  methods: {
    //得到sys_role_menu表信息字典
   /* getRoleMenuTree() {
      this.$http.get('/system-manage/role/aaa').then(resp => {
        this.roleMenuTree = resp.data.data
      })
    },*/
    //得到sys_menu表信息
    /*getMenuTree() {
      this.$http.get('/system-manage/role/menuTree').then(resp => {
        this.menuTree = resp.data.data
      })
    },*/
    /*===========================树形控件开始==================================*/
    handleCheckChange(data, checked, indeterminate) {
      const checkedList = this.$refs.treeRef.getCheckedNodes(false, true);
    },
    handleNodeClick(data, node) {

    },
    loadNode(node, resolve) {

      this.nodes = []
      var nodeChildren = []
      for (var i = 0; i < this.menuTree.length; i++) {
        if (this.menuTree[i].parentId === 0 && node.level === 0) {
          this.nodes.push(this.menuTree[i])
        }
        if (this.menuTree[i].parentId === node.menuId && node.level > 0) {
          //在nodes下面数据下面加一个children数组
          nodeChildren.push(this.menuTree[i])
          if (nodeChildren.length !== 0) {
            this.menuTree[i].children = nodeChildren
            resolve(nodeChildren)
          }
        }
      }
      this.getMenuTree()
      resolve(this.nodes)
    },

    // if (node.level > 0) {
    //
    //   resolve(this.nodes[node.level - 1])
    // }

    getCheckedKeys(val) {
      console.log(val)
    },
    echoCheckedKeys() {
      this.getCheckedKeys();
    },
    /*===========================树形控件结束==================================*/
    //查询树形控件父级数据
    loadOne() {
      this.$http.get('/system-manage/role/tree/' + this.treeId + "/" + 0).then(resp => {
        this.nodeOne = resp.data.data
      })
    },
    handleQuery() {
      this.getRoleList()
    },
    //重置查询
    resetQuery() {
      // this.queryParams = {
      this.queryParams = {
        pageNo: 1,
        pageSize: 5,
        total: 0,
        data:{},
        /*roleName: undefined,
        roleCode: undefined,
        status: undefined,
        dateRange: []*/
      }
      this.getRoleList()
      // location.reload()//页面刷新

      }

    ,
    //数据表单选择器方法
    handleSelectionChnage(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length > 1
      this.multiple = ! selection.length
    }
    ,

    //添加修改的确定
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$http.post('/role/addAndUpdate', this.form).then(resp => {
            if (resp.data.code === 200) {
              this.$message.success("操作成功");
              this.open = false
              this.getRoleList()
              this.$refs['form'].resetFields()
            } else {
              this.$message.error("操作失败");
              this.$refs['form'].resetFields()
            }
          })
        }
      })
    }
    ,

    //添加修改的取消
    cancel() {
      this.open = false
      this.$refs.form.resetFields()
      this.getRoleList()
    }
    ,
    //修改方法
    handleUpdate(row) {
      this.form = row
      this.open = true
      this.title = "修改角色"
    }
    ,
    //删除或批量删除
    handleDelete(row) {
      let roleIds = row.roleId || this.ids
      this.$confirm("确认删除选中的项吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http.delete("/role/deleteByIds/" + roleIds).then(resp => {
          if (resp.data.code === 200) {
            this.$message.success("删除成功");
            this.getRoleList();
          }
        }).catch(error =>{
          this.$message.warning("删除失败");
        })
      }).catch(error => {
        this.$message.warning("取消删除");
      })
    },

    // 打开分配权限和菜单的弹出层
    handleSelectMenu(row) {
      this.currentRoleId = row.roleId || this.ids[0]
      this.title = '---分配权限---'
      this.selectMenuOpen = true
      // 查询所有可用的菜单
      this.$http.get("/menu/getAllMenu").then(res => {
        this.menuOptions = this.handleTree(res.data.data, 'menuId')
      })
      // 根据角色ID查询当前角色拥有的哪些菜单权限
      this.$http.get("/menu/getRoleMenu/" + this.currentRoleId).then(res => {
        let menuids = []
        if (res.data.data !== null){
          for (const r of res.data.data) {
            if (r.menuType === "C")
              menuids.push(r.menuId)
          }
        }
        // console.log(JSON.stringify(menuids)+"++++++++++++++++")
        //     [17,18,19,21,80]++++++++++++++++
        this.$refs.menu.setCheckedKeys(menuids)  // 将指定的菜单项设置为选中状态
      })
    },
    handleTree(data, id, parentId, children, rootId) {
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      rootId = rootId || 0
      // 对源数据进行深度克隆
      if (!Array.isArray(data)) return []
      const cloneData = JSON.parse(JSON.stringify(data)) || []
      // 循环所有的项目
      const treeData = cloneData.filter(father => {
        const branchArr = cloneData.filter(child => {
          return father[id] === child[parentId]
        })
        branchArr.length > 0 ? father.children = branchArr : ''
        // 返回上一层
        return father[parentId] === rootId
      })
      return treeData !== '' ? treeData : data
    },
    // 保存角色和菜单权限的关系
    handleSelectMenuSubmit() {
      // 获取选中的keys
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 获取半选的keys
      const halfCheckKeys = this.$refs.menu.getHalfCheckedKeys()
      // 组合成最后的keys
      const finalKey = halfCheckKeys.concat(checkedKeys)
      console.log(JSON.stringify(this.currentRoleId)+"++++++++++++++++")
      console.log(JSON.stringify(finalKey)+"++++++++++++++++")
      this.$http.get("/menu/updateRoleMenu/" + this.currentRoleId + "/" + finalKey).then(res => {
        this.$message.success('分配成功')
        this.getRoleList()
        this.selectMenuOpen = false
      }).catch(() => {
        this.$message.error('--分配失败--')
        this.selectMenuOpen = false
      })
    },
    // 关闭分配权限的弹出层
    cancelSelectMenu() {
      this.selectMenuOpen = false
      this.menuOptions = []
    },
    //添加
    handleAdd() {
      this.open = true
      this.form = {}
      this.title = "添加角色"
    },

    // 获取数据列表
    getRoleList() {
      this.$http.post('/role/queryByPage', this.queryParams).then(res => {
        this.roleTableList = res.data.data.list
        this.total = res.data.data.total
      })
    },
    // 加载状态字典
    loadStatus() {
      this.$http.get('/role/getStatus').then(res => {
        this.statusDict = res.data.data
      })
    },
    //格式化状态
    statusFormatter(row) {
      let dictLabel = "未知";
      this.statusDict.filter(item => {
        if (item.dictValue === row.status) {
          dictLabel = item.dictLabel
        }
      })
      return dictLabel;
    },

    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNo = val
      this.getRoleList()
    },
  }
}
</script>

<style scoped>

</style>